package com.example.demo_test.Service;

import com.example.demo_test.Config.MyApplicationContextAware;
import com.example.demo_test.Dao.PersonDao;
import com.example.demo_test.Entity.*;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author zhanghong
 * @date 2021/6/6  0006 20:51
 */
@Component
@ServerEndpoint(value = "/websocket/{nickname}/{userId}")
public class WebSocketService {
    private static MessageService messageService;
    private String nickname;
    private Session session;
    private String userId;
    private static PersonDao personDao;
    @Autowired
    public  void setPersonDao(PersonDao personDao) {
        WebSocketService.personDao = personDao;
    }




    //解决不能自动注入问题，定义一个static的service，用set赋值
    @Autowired
    public void setMessageService(MessageService messageService) {
        WebSocketService.messageService = messageService;
    }



    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    //用来记录sessionId和该session进行绑定
    private static Map<String, Session> map = new HashMap<String, Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("nickname") String nickname,@PathParam("userId") String userId) {
        Map<String, Object> message = new HashMap<String, Object>();
        this.session = session;
        this.nickname = nickname;
        this.userId=userId;
        if(map.get( userId )!=null){
            return;
        }else{
            map.put( userId, session );
            webSocketSet.add( this );//加入set中
            System.out.println( "有新连接加入:" + nickname + ",当前在线人数为" + webSocketSet.size() );
            message.put( "type", 0 ); //消息类型，0-连接成功，1-用户消息
            message.put( "people", webSocketSet.size() ); //在线人数
            message.put( "name", nickname ); //昵称
            message.put( "userId",userId );
            List<User> friends=personDao.getFriends( userId );
            for (User user:friends
                 ) {
                Session session1=map.get( user.getUserId() );
                if(session1!=null){
                    session1.getAsyncRemote().sendText( new Gson().toJson( message ) );
                }
            }
            this.session.getAsyncRemote().sendText( new Gson().toJson( message ) );
        }
        personDao.updateUserStatus( userId,"在线" );
        //this.session.getAsyncRemote().sendText("恭喜" + nickname + "成功连接上WebSocket(其频道号：" + session.getId() + ")-->当前在线人数为：" + webSocketSet.size());

    }

    /**
     * 连接关闭调用的方法    
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove( this ); //从set中删除
        map.remove( userId );
        personDao.updateUserStatus( userId,"离线" );
        Map<String, Object> message = new HashMap<String, Object>();
        message.put( "type", 6 ); //消息类型6-某人离线
        message.put( "name", nickname ); //昵称
        message.put( "userId",userId );
        List<User> friends=personDao.getFriends( userId );
        for (User user:friends
        ) {
            Session session1=map.get( user.getUserId() );
            if(session1!=null){
                session1.getAsyncRemote().sendText( new Gson().toJson( message ) );
            }
        }
        System.out.println( "有一连接关闭！当前在线人数为" + webSocketSet.size() );
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("nickname") String nickname) {
        System.out.println( "来自客户端的消息-->" + nickname + ": " + message );

        //从客户端传过来的数据是json数据，所以这里使用jackson进行转换为SocketMsg对象，
        // 然后通过socketMsg的type进行判断是单聊还是群聊，进行相应的处理:
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsg socketMsg;

        try {
            socketMsg = objectMapper.readValue( message, SocketMsg.class );
            //单聊
            if (socketMsg.getType() == 1) {
                //单聊.需要找到发送者和接受者.
//                socketMsg.setFromUser( session.getId() );//发送者.
                Session fromSession = map.get( socketMsg.getFromUser().getUserId() );
                Session toSession = map.get( socketMsg.getToUser().getUserId() );
                //发送给接受者.
                if (toSession != null) {
                    //发送给发送者.
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "type", 1 );
                    m.put( "name", nickname );
                    m.put( "id", userId );
                    m.put( "msg", socketMsg.getMsg() );
                    try {
//                        fromSession.getAsyncRemote().sendText( new Gson().toJson( m ) );
                        toSession.getAsyncRemote().sendText( new Gson().toJson( m ) );
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else {
                    //发送给发送者.
                    Message mes=new Message();
                    mes.setStatus( "未读" );
                    mes.setToUser( socketMsg.getToUser().getUserId() );
                    mes.setFromUser( socketMsg.getFromUser().getUserId() );
                    mes.setDate(new Date());
                    mes.setMsg( socketMsg.getMsg() );
                    messageService.insertMessage( mes );
//                    fromSession.getAsyncRemote().sendText( "系统消息：对方不在线或者您输入的频道号不对" );
                }
                //群发消息
            } else  if(socketMsg.getType()==0){
                List<User> userList = personDao.getGroupUsers( socketMsg.getGroupId() );
                Map<String, Object> m = new HashMap<String, Object>();
                m.put( "type", 2 );
                m.put( "name", nickname );
                m.put( "id", userId );
                m.put( "msg", socketMsg.getMsg() );
                m.put( "groupId",socketMsg.getGroupId() );
                //群发消息
                broadcast(m,userList);
            }else if(socketMsg.getType()==2){
                Session session1=map.get( socketMsg.getToUser().getUserId() );
                if(session1!=null){
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "type", 4 );
                    m.put( "id", socketMsg.getFromUser().getUserId() );
                    session1.getAsyncRemote().sendText( new Gson().toJson( m ) );
                }
            }else if(socketMsg.getType()==3){
                Session session1=map.get( socketMsg.getToUser().getUserId() );
                if(session1!=null){
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put( "type", 5 );
                    m.put( "name",socketMsg.getFromUser().getUserName() );
                    session1.getAsyncRemote().sendText( new Gson().toJson( m ) );
                }
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用   
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println( "发生错误" );
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast( Map<String, Object> m,List<User> userList) {
        for (User item : userList) {
            Session session=map.get( item.getUserId() );
            if(session!=null) {
                session.getAsyncRemote().sendText( new Gson().toJson( m ) );//异步发送消息.
            }
        }
        GroupMessage groupMessage=new GroupMessage();
        groupMessage.setMsg( (String) m.get( "msg" ) );
        groupMessage.setFromUser( (String) m.get( "id" ) );
        groupMessage.setDate( new Date() );
        groupMessage.setGroupEid( (Integer) m.get( "groupId" ) );
        messageService.addGroupMessage( groupMessage );
    }
    public static boolean isLogin(String userId){
        if(map.get( userId )!=null){
            return true;
        }else{
            return false;
        }
    }
    public static void pushReqRecord(ReqRecord reqRecord){
        Map<String, Object> m = new HashMap<String, Object>();
        m.put( "type", 3 );
        m.put( "reqRecord", reqRecord );
        if(map.get( reqRecord.getToUser() )!=null){
            map.get( reqRecord.getToUser() ).getAsyncRemote().sendText( new Gson().toJson( m ) );
        }
    }
    public static void sendMessageForHeartbeat(){
        Map<String, Object> m = new HashMap<String, Object>();
        m.put( "message","Heartbeat" );
        for (Session s:map.values()
             ) {
            s.getAsyncRemote().sendText( new Gson().toJson( m ) );
        }
    }
}
